<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="gtitle" style="margin-bottom: 20px"><a-icon type="info-circle" style="color: #108ee9" theme="filled"/>管理员列表</div>
      <a-row style="margin-top: 20px;margin-bottom: 20px;">
        <a-button type="primary" style="margin-left: 15px" @click='adduser()'>添加</a-button>
        <a-button type="primary" style="margin-left: 15px" @click="modifyuser()">修改</a-button>
        <a-button type="primary" style="margin-left: 15px" @click="deleteuser()">删除</a-button>
        <a-button type="primary" style="margin-left: 15px" @click="resetpassword()">重置密码</a-button>
      </a-row>

      <a-table :columns="columns" :data-source="data" :row-selection="rowSelection" :pagination="tablepagination"  @change="tablechange">
        <template slot="type" slot-scope="text, record">
          {{text==0?'内置用户':'内部员工'}}
        </template>
        <template slot="departmentGroupIds" slot-scope="text, record">
          {{getgroupname(text)}}
        </template>
        <template slot="role" slot-scope="text, record">
          {{getrolename(text)}}
        </template>
        <template slot="appleIps" slot-scope="text, record">
          <div v-for="item in parseToarray(text)">
            {{item.value}}
          </div>
        </template>
      </a-table>
      <div class="gtitle" style="margin-bottom: 20px;margin-top: 20px"><a-icon type="info-circle" style="color: #108ee9" theme="filled"/>角色及权限管理</div>
      <a-row style="margin-top: 20px;margin-bottom: 20px;">
        <a-button type="primary" style="margin-left: 15px" @click="addsamelevel()">添加同级角色</a-button>
        <a-button type="primary" style="margin-left: 15px" @click="addsublevel()">添加下级级角色</a-button>
        <a-button type="primary" style="margin-left: 15px" @click="modifyrolename()">修改</a-button>
        <a-button type="primary" style="margin-left: 15px" @click="deleterole()">删除</a-button>
      </a-row>
      <a-row style="margin-top: 20px;margin-bottom: 20px;">
        <a-col :span="6">
          <div class="rolelist">
            <a-tree :show-line="true"
                    :expanded-keys="expandedKeys"
                    :auto-expand-parent="autoExpandParent"
                    :tree-data="treedata"
                    @expand="onExpand"
                    @select="selecttree"
            >
            </a-tree>
          </div>
        </a-col>
        <a-col :span="12" :offset="1">
          <div class="rolelist" v-if="roleId !== ''">
            <ATransfer
              class="tree-transfer"
              :data-source="dataSource"
              :target-keys="targetKeys"
              :render="item => item.title"
              :show-select-all="false"
              @change="onChange"
              :titles="['可选权限','已选权限']"
            >
              <template
                slot="children"
                slot-scope="{ props: { direction, selectedKeys }, on: { itemSelect } }"
              >
                <a-tree
                  v-if="direction === 'left'"
                  blockNode
                  checkable
                  checkStrictly
                  defaultExpandAll
                  :checkedKeys="[...selectedKeys, ...targetKeys]"
                  :treeData="permissiontree"
                  @check="
            (_, props) => {
              onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
            }
          "
                  @select="
            (_, props) => {
              onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
            }
          "
                />
              </template>
            </ATransfer>
          </div>
        </a-col>
      </a-row>

    </a-card>
    <Mymodal
      ref="mymodal"
    ></Mymodal>
  </page-header-wrapper>
</template>

<script>
  import {UserType} from '../../utils/constant'
  import Mymodal from '@/components/mycomp/mymodal.vue'
  import ATransfer from 'ant-design-vue/es/transfer'
  import {} from '../../utils/constant'
  import { getDepartmentList } from '@/api/department'
  import {
    getrolelist,
    getuserlist,
    addrole,
    deleterole,
    getroleinfo,
    updatepermission,
    adduser,
    deleteuser, resetpassword
  } from '@/api/user'
  import { deletegroup } from '@/api/assets'
  import { deletepolicy } from '@/api/policy'
  export default {
    name: 'PatchUpdateManage',
    components: { ATransfer,Mymodal },
    data() {
      return {
        UserType,
        data:[],
        columns:[
          {
            title:'用户',
            key:'nickname',
            dataIndex: 'nickname',
          },
          {
            title:'姓名',
            key:'username',
            dataIndex: 'username',
          },
          {
            title:'角色',
            key:'role',
            dataIndex: 'role',
            scopedSlots: { customRender: 'role' }
          },
          {
            title:'用户类型',
            key:'type',
            dataIndex: 'type',
            scopedSlots: { customRender: 'type' }
          },
          {
            title:'资产管理权限',
            key:'departmentGroupIds',
            dataIndex: 'departmentGroupIds',
            scopedSlots: { customRender: 'departmentGroupIds' }
          },
          {
            title:'电子邮箱',
            key:'email',
            dataIndex: 'email',
          },
          {
            title:'允许登录的IP范围',
            key:'appleIps',
            dataIndex: 'appleIps',
            scopedSlots: { customRender: 'appleIps' }
          },
        ],
        rowSelection:{
          onChange: (selectedRowKeys, selectedRows) => {
            this.selectarray = selectedRows
            document.getElementById('app').style.transform = `scale(1)`
            document.getElementById('app').style.transformOrigin = `0 0`
            document.getElementById('app').style.height = `100%`
            setTimeout(()=>{
              var scale = (window.innerWidth-20)/1900
              document.getElementById('app').style.transform = `scale(${scale})`
              document.getElementById('app').style.transformOrigin = `0 0`
              document.getElementById('app').style.height = `${100/scale}%`
            },0)
          },
          onSelect: (record, selected, selectedRows) => {
          },
          onSelectAll: (selected, selectedRows, changeRows) => {
          },
        },
        tablepagination:{
          showTotal:(total, range) => {return `共搜索到${total}条数据`},
          current:1,
          total:0
        },
        selectarray:[],
        expandedKeys:[],
        autoExpandParent:true,
        dataSource:[],
        permissiontree:[
          { key: '资产管理', title: '资产管理',checkable:false,selectable:false,children: [
              { key: '资产信息', title: '资产信息' },
              { key: '资产分组设置', title: '资产分组设置' },
              { key: '资产发现设置', title: '资产发现设置' },
            ],},
          { key: '补丁管理', title: '补丁管理',checkable:false,selectable:false,children: [
              { key: '补丁库', title: '补丁库' },
              { key: '补丁组管理', title: '补丁组管理' },
              { key: '黑名单补丁', title: '黑名单补丁' },
              { key: '补丁更新管理', title: '补丁更新管理' },
              { key: '文件库', title: '文件库' },
            ],},
          { key: '策略管理', title: '策略管理',checkable:false,selectable:false,children: [
              { key: '测试补丁分发', title: '测试补丁分发' },
              { key: '正式补丁分发', title: '正式补丁分发' },
              { key: '人工补丁分发', title: '人工补丁分发' },
              { key: '普通文件分发', title: '普通文件分发' },
            ],},
          { key: '数据查询', title: '数据查询',checkable:false,selectable:false,children: [
              { key: '策略执行日志', title: '策略执行日志' },
              { key: '漏洞扫描日志', title: '漏洞扫描日志' },
              { key: '操作日志', title: '操作日志' },
            ],},
          { key: '系统配置', title: '系统配置',checkable:false,selectable:false,children: [
              { key: '通用配置', title: '通用配置' },
              { key: '网络配置', title: '网络配置' },
              { key: '用户配置', title: '用户配置' },
              { key: '系统安全', title: '系统安全' },
              { key: '备份管理', title: '备份管理' },
              { key: '级联配置', title: '级联配置' },
              { key: '告警配置', title: '告警配置' },
              { key: '授权管理', title: '授权管理' },
            ],},
        ],
        targetKeys: [],
        grouptreedata:[],
        treedata:[],
        roleId:'',
        groupMap:{},
        assetsgroupMap:{}
      }
    },
    mounted() {
      this.$info(
        {
          title:'提示',
          content:'测试Lisence未授权！',
          onOk:()=> {
            this.$router.push({ path: '/overview/overview' })
          },
        }
      )
      this.loaddepartment()
      this.getrolelistfunc().then(res=>{
        this.getuserlist()
      })

      this.flatten(this.permissiontree)
    },
    methods:{
      tablechange(pagination){
        this.tablepagination = pagination
        this.getuserlist()
      },
      getids(){
        let arry = []
        for(let i in this.selectarray){
          arry.push(this.selectarray[i].id)
        }
        let id = arry.join(',')
        return id
      },
      resetpassword(){
        if(!this.selectarray || this.selectarray.length == 0){
          this.$message.info('请先选择一条数据')
          return
        }
        let id = this.getids()
        this.$confirm({
          title: '是否重置密码?',
          okText: '是',
          okType: 'primary',
          cancelText: '否',
          onOk:()=> {
            resetpassword({ids:id}).then(res=>{
              this.$message.success('操作成功')
            })
          }
        })
      },
      deleteuser(){
        if(!this.selectarray || this.selectarray.length == 0){
          this.$message.info('请先选择一条数据')
          return
        }
        let id = this.getids()
        this.$confirm({
          title: '是否确认删除数据?',
          okText: '是',
          okType: 'danger',
          cancelText: '否',
          onOk:()=> {
            deleteuser({ids:id}).then(res=>{
              this.$message.success('操作成功')
              this.getuserlist()
            })
          }
        });
      },
      parseToarray(txt){
        if(!txt){
          return []
        }else{
          return JSON.parse(txt).ip
        }
      },
      getgroupname(ids){
        if(!ids) return ''
        let arry = ids.split(',')
        if(arry[0].title == 'all') return '全部'
        let str = []
        for(let i in arry){
          str.push(this.assetsgroupMap[arry[i]].title)
        }
        return str.join(',')
      },
      getrolename(text){
        if(!text) return ''
        return this.groupMap[text].title
      },
      getuserlist(){
        let params = {}
        params.pageNo = this.tablepagination.current
        params.pageSize = 10
        getuserlist(params).then(res=>{

          let record = res.data.records
          for(let i in record){
            record[i].key =record[i].id
          }
          this.data = record
          this.tablepagination.total = res.data.total
        })
      },
      onChange(targetKeys) {
        this.targetKeys = targetKeys;
        updatepermission({
          id:this.roleId,
          menuNames:targetKeys.join(',')
        })
      },
      getPermisson(){
        getroleinfo({id :this.roleId}).then(res=>{
          this.targetKeys = res.data.menuNames?res.data.menuNames.split(','):[]
        })
      },
      addsamelevel(){
        if(!this.roleId){
          this.$message.info('请先选择一个角色')
          return
        }
        let modalinfo = {
          title:'新建角色',
          list:[
            {name:'name',label:'角色名称',require:true,type:'input',errortip:'请输入名称'},
          ],
          ok:this.createroleok.bind(this),
          moreinfo:{
            pId:this.pId
          }
        }
        this.$refs.mymodal.showmodal(modalinfo)
      },
      modifyrolename(){
        if(!this.roleId){
          this.$message.info('请先选择一个角色')
          return
        }

        let modalinfo = {
          title:'修改角色',
          list:[
            {name:'name',label:'角色名称',require:true,type:'input',errortip:'请输入名称',value:this.groupMap[this.roleId].title},
          ],
          ok:this.createroleok.bind(this),
          moreinfo:{
            pId:this.groupMap[this.roleId].pId,
            id:this.roleId
          }
        }
        this.$refs.mymodal.showmodal(modalinfo)
      },
      addsublevel(){
        if(!this.roleId){
          this.$message.info('请先选择一个角色')
          return
        }

        let modalinfo = {
          title:'新建分组',
          list:[
            {name:'name',label:'角色名称',require:true,type:'input',errortip:'请输入名称'},
          ],
          ok:this.createroleok.bind(this),
          moreinfo:{
            pId:this.roleId
          }
        }
        this.$refs.mymodal.showmodal(modalinfo)
      },
      createroleok(params){
        addrole(params).then(res=>{
          this.$message.success('操作成功')
          this.getrolelistfunc()
        })
      },
      getrolelistfunc(){
        return getrolelist({}).then(res=>{
          if(res.data){
            this.groupMap = {}
            this.treedata = this.transtotree(res.data)
            let list = this.getallnode(this.treedata)
            for(let i in list){
              this.groupMap[list[i].key] = list[i]
            }
          }
        })
      },
      loaddepartment(){
        getDepartmentList({isHaveWhole:1}).then(res=>{
          if(res.data){
            this.grouptreedata = this.transtotree(res.data)
            this.grouptreedata = [{ key: 'all', title: '全部',value:'all'},...this.grouptreedata[0].children]

            this.assetsgroupMap = {}
            let list = this.getallnode(this.grouptreedata)
            for(let i in list){
              this.assetsgroupMap[list[i].key] = list[i]
            }
          }
        })
      },
      deleterole(){
        if(!this.roleId){
          this.$message.info('请先选择一个角色')
          return
        }
        this.$confirm({
          title: '是否确认删除数据?',
          okText: '是',
          okType: 'danger',
          cancelText: '否',
          onOk:()=> {
            deleterole({ids:this.roleId}).then(res=>{
                this.roleId = ''
                this.getrolelistfunc()
            })
          }
        });
      },
      adduser(){
        let modalinfo = {
          title:'添加用户',
          list:[
            {name:'nickname',label:'用户名称',require:true,type:'input',errortip:'请输入用户名称',placeholder:'支持大小写字母，数字'},
            {name:'username',label:'姓名',require:true,type:'input',errortip:'请输入姓名',placeholder:'支持中文，字母，数字'},
            {name:'password',label:'输入密码',require:true,type:'password',errortip:'请输入密码',placeholder:'支持大小写字母，数字，特殊字符'},
            {name:'confirmpassword',label:'再次输入密码',require:true,type:'password',errortip:'请再次输入密码',placeholder:'支持大小写字母，数字，特殊字符'},
            {name:'role',label:'角色',require:true,type:'tree',errortip:'请选择角色',treedata:this.treedata},
            {name:'type',label:'用户类型',type:'select',require:true,errortip:'请选择用户类型',selectdata:this.UserType},
            {name:'email',label:'电子邮件',type:'input'},
            {name:'departmentGroupIds',label:'选择管理的资产组',type:'multitree',treedata:this.grouptreedata},
            {name:'appleIps',label:'允许登录的IP范围',type:'iplist'},
          ],
          ok:this.adduserfunc.bind(this),
          moreinfo:{
          }
        }
        this.$refs.mymodal.showmodal(modalinfo)
      },
      modifyuser(){
        if(!this.selectarray || this.selectarray.length == 0){
          this.$message.info('请先选择一条数据')
          return
        }
        if(this.selectarray && this.selectarray.length >1){
          this.$message.info('此操作只支持一条数据')
          return
        }

        let item = this.selectarray[0]

        let modalinfo = {
          title:'修改规则',
          list:[
            {name:'nickname',label:'用户名称',require:true,type:'input',errortip:'请输入用户名称',placeholder:'支持大小写字母，数字',value:item.nickname},
            {name:'username',label:'姓名',require:true,type:'input',errortip:'请输入姓名',placeholder:'支持中文，字母，数字',value:item.username},
            {name:'role',label:'角色',require:true,type:'tree',errortip:'请选择角色',treedata:this.treedata,value:item.role},
            {name:'type',label:'用户类型',type:'select',require:true,errortip:'请选择用户类型',selectdata:this.UserType,value:item.type.toString()},
            {name:'email',label:'电子邮件',type:'input',value:item.email},
            {name:'departmentGroupIds',label:'选择管理的资产组',type:'multitree',treedata:this.grouptreedata,value:item.departmentGroupIds.split(',')},
            {name:'appleIps',label:'允许登录的IP范围',type:'iplist',value:item.appleIps},
          ],
          ok:this.adduserfunc.bind(this),
          moreinfo:{
            id:item.id
          }
        }
        this.$refs.mymodal.showmodal(modalinfo)
      },
      adduserfunc(params){
        if(params.password && params.password != params.confirmpassword){
          this.$message.error('两次输入密码不一致')
          return
        }
        params.departmentGroupIds = params.departmentGroupIds.join(',')
        adduser(params).then(res=>{
          this.$message.success('操作成功')
          this.getuserlist()
        })
      },

      onChecked(_, e, checkedKeys, itemSelect) {
        const { eventKey } = e.node;
        itemSelect(eventKey, !this.isChecked(checkedKeys, eventKey));
      },
      selecttree(key,e){
        if(e.node.$parent.value){
          this.pId = e.node.$parent.value
        }else{
          this.pId = 0
        }
        this.roleId = key[0]
        this.getPermisson()
      },
      onExpand(expandedKeys) {
        this.expandedKeys = expandedKeys;
        this.autoExpandParent = false;
      },
      isChecked(selectedKeys, eventKey) {
        return selectedKeys.indexOf(eventKey) !== -1;
      },
      flatten(list) {
        list.forEach(item => {
          this.dataSource.push(item);
          if(item.children){
            this.flatten(item.children);
          }
        });
      },
      transtotree(list){
        let arry = []
        for(let i in list){
          let json = {}
          json.title = list[i].name
          json.key = list[i].id
          json.value = list[i].id
          json.pid = list[i].pId
          if(list[i].childNode){
            json.children = this.transtotree(list[i].childNode)
          }
          arry.push(json)
        }
        return arry
      },
      getallnode(list){
        let array = []
        for(let i =0;i<list.length;i++){
          array.push(list[i])
          if(list[i].children){
            array = array.concat(this.getallnode(list[i].children))
          }
        }
        return array
      },
    }
  }
</script>
<style lang="less">
  @import "~ant-design-vue/es/transfer/style/index.less";
  .tree-transfer .ant-transfer-list:first-child {
    width: 50%;
    flex: none;
  }
</style>
<style lang="less"  scoped>

  .gtitle{
    background-color: #e6f3fc;
    line-height: 40px;
    padding-left: 20px;
    color: #333;
    font-weight: bold;

    i{
      margin-right: 10px;
    }
  }
  .rowtxt,.ant-radio-group{
    line-height: 32px;

  }
  .ant-radio-group{
    width: 100%;
  }
  .rowspan{
    display: inline-block;
    width: 150px;
  }
  .showtxt{
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 0 10px;
    height: 120px;
    overflow-y: auto;
  }
  .rowmb{
    margin-bottom: 10px;
  }
  .blue{
    color: #3366FF;
  }
  .iplist{
    border: 1px solid #ddd;
    padding: 5px;
    min-height: 100px;
    line-height: 30px;
    div:hover{
      background-color: #efefef;
    }
    .icon{
      color: red;
      cursor: pointer;
      line-height: 30px;
      float: right;
      margin-right: 20px;
    }
  }
  .rolelist{
    border: 1px solid #ddd;
    border-radius: 4px;
    padding:5px;
    min-height: 400px;
  }
</style>
